package com.teaching.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teaching.common.Result;
import com.teaching.dto.AttachDTO;
import com.teaching.entity.Attach;
import com.teaching.service.AttachService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;


/**
 * 附件表
 *
 * @author xubb
 * @date 2021-03-22 15:27:55
 */
@RestController
@RequestMapping("/attach")
@Api(value = "attach", tags = "附件表管理")
public class AttachController {

    @Resource
    private AttachService attachService;


    @PostMapping("/listByGroupGuid")
    @ApiOperation(value = "根据groupid获取附件列表")
    public Result listByGroupGuid(@RequestBody AttachDTO dto) {
        QueryWrapper<Attach> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Attach::getGroupGuid, dto.getGroupGuid());
        List<Attach> list = attachService.list(queryWrapper);
        return Result.success(list);
    }


    @PostMapping("/uploadFile")
    @ApiOperation(value = "通用上传文件")
    public Result uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("groupGUid") String groupGUid, @RequestParam("groupType") String groupType) {
        try {
            return Result.success(attachService.save(file, groupGUid, groupType));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("异常");
        }
    }


    @GetMapping("/download")
    @ApiOperation(value = "通过附件GUid下载文件")
    public ResponseEntity<FileSystemResource> downloadFile(@RequestParam("attachGuid") String attachGuid, HttpServletResponse response) throws UnsupportedEncodingException {

        Attach attachInfo = attachService.getById(attachGuid);
        String fullPath = attachInfo.getAttachPath();
        String fileName = attachInfo.getAttachName();
        File file = new File(fullPath);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            return attachService.export(file);
        }
        return null;
    }


    @PostMapping("/deleteFile")
    @ApiOperation(value = "删除附件")
    public Result deleteFileByGuid(@RequestBody AttachDTO dto) {
        Attach attachInfo = attachService.getById(dto.getAttachID());
        boolean flag = FileUtil.del(attachInfo.getAttachPath());
        attachService.removeById(attachInfo.getAttachId());
        return Result.success();

    }
}
